<?php

namespace core;

use src\common\Request;
use src\common\Response;
use src\common\RouterMatch;


class RequestHandler
{
    public static function handle()
    {
        [$controller, $action] = RouterMatch::match();

        // 判断类文件是否存在
        $php_file = CONTROLLER_DIR . str_replace('\\', '/', $controller) . '.php';
        if (!file_exists($php_file)) Response::err("Controller $controller not found");

        // 实例化控制器
        $controllerClass = "src\controller\\$controller";
        $_controller = Container::get($controllerClass);

        try {
            Request::init();
            // 调用控制器的方法
            $resp = $_controller->$action();
        } catch (\Throwable $e) {
            Response::err($e->getMessage());
        }

        if ($resp) {
            if (is_array($resp)) {
                Response::json($resp);
            } else {
                Response::text($resp);
            }
        }
    }
}
